<template>
  <div class="page-container">
    <ScrollTab :tabs="tabs" :onTabItemClick="onTabItemClick" ref="scrollTab"/>
    <div class="swiper-container" ref="swiperContainer">
      <div class="swiper-wrapper">
        <div class="swiper-slide" v-for="item in tabs">{{ item.name }}</div>
      </div>
    </div>
  </div>
</template>
<script>
import {ref, onMounted, onUnmounted} from 'vue'
import ScrollTab from "/src/components/common/scroll-tab";

export default {
  name: 'About',
  components: {
    ScrollTab,
  },
  setup() {
    const scrollTab = ref()
    const swiperContainer = ref()
    const tabs = [
      {name: '熟食'},
      {name: '水果水果水果'},
      {name: '轻食'},
      {name: '零食水果'},
      {name: '蔬菜菜'},
      {name: '肉蛋水果水果水果水果'},
      {name: '粮油'},
      {name: '酒饮'},
      {name: '速食'},
      {name: '粮油'},
      {name: '水产'},
      {name: '火锅'},
    ]
    const Swiper = require('/src/libs/swiper-4.5.3')
    let swiper;
    let useSwiperProgress = true
    const initSwiper = () => {
      let lockIndex = -1;
      swiper = new Swiper(
          swiperContainer.value,
          {
            resistanceRatio: 0,
            watchSlidesProgress: true,
            on: {
              slideChange() {
                if (useSwiperProgress) {
                  scrollTab.value.setCurIndex(this.activeIndex)
                }
              },
              progress() {
                if (useSwiperProgress) {
                  if (lockIndex === -1) {
                    lockIndex = this.activeIndex
                  }
                  let v = this.slides[lockIndex].progress
                  scrollTab.value.scrollTo(lockIndex, v)
                  if (v === Math.floor(v)) {
                    lockIndex = -1;
                  }
                }
              },
            },
          }
      )
    }

    let timer;
    const onTabItemClick = (index) => {
      if (swiper) {
        if (timer) {
          clearTimeout(timer)
        }
        useSwiperProgress = false;
        swiper.slideTo(index, 250, false)
        timer = setTimeout(() => {
          useSwiperProgress = true
          timer = null
        }, 250)
      }
    }

    onMounted(initSwiper)
    onUnmounted(() => {
      if (timer) {
        clearTimeout(timer)
        timer = null
      }
    })

    return {
      scrollTab,
      tabs,
      onTabItemClick,
      swiperContainer,
    }
  }
};
</script>
<style scoped>
.page-container {
  display: flex;
  flex-direction: column;
}

.swiper-container {
  flex: 1;
  width: 100%;
}


</style>
